//
//  MTTaskInviteViewController.swift
//  MT
//
//  Created by ooops on 2020/5/26.
//  Copyright © 2020 张强. All rights reserved.
//


import UIKit
import GrowingTextView
import MTCategory
import YPNavigationBarTransition
import RxSwift

extension MTTaskInviteViewController: TagListViewDelegate {
    // MARK: TagListViewDelegate
    func tagPressed(_ title: String, tagView: TagView, sender: TagListView) {
        debugPrint("Tag pressed: \(title), \(sender)")
        let tags = self.tagListView.selectedTags()
        if tags.count >= 3, tagView.isSelected == false {
            MBProgressHUD_JChat.show(text: "最多选择三个标签", view: self.view, 1)
            tagView.isSelected = false
            return
        }
        tagView.isSelected = !tagView.isSelected
    }
    
    func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) {
        debugPrint("Tag Remove pressed: \(title), \(sender)")
        sender.removeTagView(tagView)
        selectedTags.removeAll { (s) -> Bool in
            s == title
        }
    }
}

class MTTaskInviteViewController: BaseViewController {
    
    var pushId: String?
    
    fileprivate var selectedTags: [String] = []
    
    /// MTProvider
    fileprivate lazy var taskProvider: MTProvider<MTCreateTaskAPI> = {
        return MTProvider<MTCreateTaskAPI>(plugins: [])
    }()
    
    convenience init(pushId: String) {
        self.init()
        self.pushId = pushId
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "报名申请验证"
        setupUI()
        makeConstraint()
        
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.text.x9b9b9b, NSAttributedString.Key.font:PingFangSCSemiboldFont(16)]
        
        invitationMessageView.rx.text.orEmpty.asObservable().subscribe(onNext: {[weak self] (text) in
            guard let weakSelf = self else { return }
            weakSelf.inviteJoinButton.backgroundColor = text.count > 0 ? UIColor(hex: 0xffc000) : UIColor(hex: 0xe6e6e6)
        }).disposed(by: globalDisposedBag)
        
        userIconView.mtSetImage(UserCenter.default.headerUrl, nil)
        nickNameLabel.text = UserCenter.default.nickname
        levelLabel.text = UserCenter.default.levelName
        
        if UserCenter.default.age != nil && UserCenter.default.area != nil {
            areaLabel.text = "\(UserCenter.default.age ?? 0)岁 | \(UserCenter.default.area ?? "")"
        } else if UserCenter.default.area == nil {
            areaLabel.text = "\(UserCenter.default.age ?? 0)岁"
        } else {
            areaLabel.text = "\(UserCenter.default.area ?? "")"
        }
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: inviteJoinButton)
    }
    
    private func setupUI() {
        view.addSubview(userIconView)
        view.addSubview(nickNameLabel)
        view.addSubview(levelLabel)
        view.addSubview(areaLabel)
        
        view.addSubview(invitationMessageView)
        
        view.addSubview(lineView)
        view.addSubview(tagTipLabel)
        view.addSubview(tagListView)
        
//        view.addSubview(inviteJoinButton)
        
    }
    
    private func makeConstraint() {
        userIconView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight + 10)
            make.left.equalToSuperview().offset(10)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        
        nickNameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(userIconView)
            make.left.equalTo(userIconView.snp.right).offset(10)
        }
        
        areaLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(userIconView)
            make.left.equalTo(userIconView.snp.right).offset(10)
        }
        
        levelLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(nickNameLabel)
            make.left.equalTo(nickNameLabel.snp.right).offset(10)
        }
        
        
        invitationMessageView.snp.makeConstraints { (make) in
            make.top.equalTo(userIconView.snp.bottom).offset(14)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(146)
            make.centerX.equalToSuperview()
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(invitationMessageView.snp.bottom).offset(10)
        }
        
        tagTipLabel.snp.makeConstraints { (make) in
            make.left.equalTo(lineView)
            make.top.equalTo(lineView.snp.bottom).offset(10)
        }
        
        tagListView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(tagTipLabel.snp.bottom).offset(10)
            make.height.equalTo(80)
        }
        
//        inviteJoinButton.snp.makeConstraints { (make) in
//            make.centerX.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset)
//            make.size.equalTo(CGSize(width: 332, height: 49))
//        }
        
    }
    
    lazy var invitationMessageView: GrowingTextView = {
        let textView = GrowingTextView()
        textView.frame = CGRect(x: 54, y: 190, width: 300, height: 100)
        textView.layer.cornerRadius = 3.0
        textView.placeholder = ""
        textView.font = PingFangSCMediumFont(12)
        textView.maxLength = 50
        textView.minHeight = 146
        textView.placeholder = "请填写验证信息"
        textView.maxHeight = 146
        textView.backgroundColor = .white
        textView.layer.cornerRadius = 8
        textView.layer.borderColor = UIColor(hex: 0x9b9b9b).cgColor
        textView.layer.borderWidth = 1
        textView.contentInset = UIEdgeInsets(top: 5, left: 8, bottom: 8, right: 8)
        return textView
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var tagTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x161616
        l.text = "选择个人标签"
        return l
    }()
    
    lazy var tagListView: TagListView = {
        let v = TagListView()
        v.delegate = self
        v.tagSelectedBackgroundColor = UIColor(hex: 0x426bf2)
        v.textFont = PingFangSCMediumFont(14)
        v.textColor = UIColor.text.x9b9b9b
        //v.shadowRadius = 8
        //v.shadowOpacity = 1
        v.tagBackgroundColor = .white
        v.cornerRadius = 8
        v.paddingX = 10
        v.paddingY = 8
        v.marginX = 10
        v.marginY = 10
        v.borderColor = UIColor.text.x9b9b9b
        v.borderWidth = 1
        //v.shadowColor = UIColor.black
        //v.shadowOffset = CGSize(width: 1, height: 1)
        v.addTags(["不迟到", "有才艺", "会剪辑", "粉丝多", "表演能力强", "资金实力厚"])
        v.alignment = .left
        return v
    }()
    
    lazy var userIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
        imageV.layer.masksToBounds = true
        return imageV
    }()
    
    lazy var nickNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        return l
    }()
    
    lazy var levelLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(10)
        l.textColor = UIColor.white
        return l
    }()
    
    lazy var areaLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        return l
    }()
    
//    lazy var inviteJoinButton: UIButton = {
//        let btn = UIButton(type: .custom)
//        btn.setTitle("下一步", for: .normal)
//        btn.setTitleColor(UIColor.white, for: .normal)
//        btn.addTarget(self, action: #selector(MTTaskInviteViewController.inviteJoinClub), for: .touchUpInside)
//        btn.backgroundColor = UIColor(hex: 0xffc000)
//        return btn
//    }()
    
    lazy var inviteJoinButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("下一步", for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        if let image: UIImage = UIImage.init(color: UIColor(hex: 0xffc000), size: CGSize(width: 60, height: 24))?.byRoundCornerRadius(12) {
            btn.setBackgroundImage(image, for: .normal)
            btn.addTarget(self, action: #selector(MTTaskInviteViewController.inviteJoinClub), for: .touchUpInside)
        }
        return btn
    }()
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.invitationMessageView.resignFirstResponder()
    }
    
    
    //MARK: - click func
    @objc func inviteJoinClub() {
        guard let pushId = self.pushId else { return }
        guard let remark = self.invitationMessageView.text else { return }
        
        for (_, v) in self.tagListView.selectedTags().enumerated() {
            if let tag = v.currentTitle {
                self.selectedTags.append(tag)
            }
        }
        let parameters: [String : Any] = ["partyId" : pushId, "ramark" : remark, "type" : 0, "userName" : JMSGUser.myInfo().username, "userTag" : self.selectedTags]
        MTCreateTaskTool.joinPartyTask(provider: taskProvider, parameters: parameters, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                DispatchQueue.main.async {
                    MBProgressHUD_JChat.show(text: "申请已发送, 请耐心等待", view: weakSelf.view, 1)
                    DispatchQueue.main.after(0.25) {
                        weakSelf.pop()
                    }
                }
            } else {
                if let msg = model?.message {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.show(text: msg, view: weakSelf.view, 1)
                    }
                }
            }
        }) { (error) in
            if let r = error as? NSError, let msg = r.userInfo["message"] as? String {
                DispatchQueue.main.async {
                    MBProgressHUD_JChat.show(text: msg, view: self.view, 1)
                }
            }
        }
    }
}


extension MTTaskInviteViewController {

//    override func yp_navigationBarTintColor() -> UIColor! {
//        return UIColor(hex: 0xFFFFFF)
//    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack, .backgroundStyleOpaque, .showShadowImage]
    }

//    override func yp_navigationBackgroundColor() -> UIColor! {
//        return UIColor(hex: 0x000000)
//    }
}
